#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import operator
from functools import reduce

import cv2
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from PIL import ImageStat


class Fault(object):
    """
    故障检测类
    """

    def __init__(self, ImgPath):
        print '载入图片：' + ImgPath
        self.ImgPath = ImgPath

    def start(self):
        print '开始执行故障检测'
        # self.isHang()
        # self.isImgDim()
        if self.isContrast(r'img\1.jpg') <= 300:  # 视频信号判断
            return '无视频信号'
        elif self.isBrightness() <= 35:  # 黑屏判断
            return '黑屏'
        elif self.isImgDim() <= 1340:
            return '画面模糊'
        else:
            return '0'

    def isImgDim(self):
        """
        图片模糊程度
        :return: int
        """
        print '开始识别模糊程度'
        image = cv2.imread(self.ImgPath)
        dim = int(cv2.Laplacian(image, cv2.CV_64F).var())
        print '模糊度:', dim
        return dim

    def isContrast(self, contrastImg):
        """
        图片差异对比
        :return: int
        """
        print '开始差异对比'
        try:
            inputImg = Image.open(self.ImgPath).convert('L')
            contrastImg = Image.open(contrastImg).convert('L')

            # 裁切图片  上下 裁剪50像素
            cropedIm1 = inputImg.crop((0, 50, 352, 238))
            cropedIm2 = contrastImg.crop((0, 50, 352, 238))

            # cropedIm1.save(r'temp\1.jpg')
            # cropedIm2.save(r'temp\2.jpg')
            h1 = cropedIm1.histogram()
            h2 = cropedIm2.histogram()
            res = int(math.sqrt(reduce(operator.add, list(map(lambda a, b: (a - b) ** 2, h1, h2))) / len(h1)))
            # print '差异值:', res
            return res
        except IOError:
            pass

    def isBrightness(self):
        """
        检查图片亮度
        :return: int
        """
        print '开始亮度检测'
        im = Image.open(self.ImgPath)
        stat = ImageStat.Stat(im)
        gs = (math.sqrt(0.241 * (r ** 2) + 0.691 * (g ** 2) + 0.068 * (b ** 2))
              for r, g, b in im.getdata())
        res = int(sum(gs) / stat.count[0])
        print '亮度：', res
        return res

    def isHang(self):
        """
        检查白屏照片
        :return:
        """
        print '开始检查白屏照片'
        # img = Image.open(self.ImgPath)
        # print img.histogram()

        image = Image.open(self.ImgPath).convert("L")
        image_array = np.array(image)
        print image_array

        plt.subplot(2, 1, 1)
        plt.imshow(image, cmap=cm.gray)
        plt.axis("off")
        plt.subplot(2, 1, 2)
        plt.hist(image_array.flatten(), 256)  # flatten可以将矩阵转化成一维序列
        plt.show()
        return None
